<?php
/*
 * @Author: 偻儸小卒[EdisonLiu_]
 * @Date: 2021-06-23 15:05:51
 * @LastEditors: 偻儸小卒[EdisonLiu_]
 * @LastEditTime: 2021-06-24 14:32:14
 * @Description: 
 */

namespace App\Http\Controllers\AdminApi\Category;

use App\Http\Controllers\Controller;
use App\Http\Models\Admin\ClassifyPermissions;

use App\Http\Models\Admin\Category;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CategoryController extends Controller
{
    // 查列表
    public function list(Request $request)
    {
        $limit = $request->get('limit');
        $title = trim($request->get('title'));
        $sort = getSort($request);
        // var_dump($sort);die;
        // 
        if(!empty($title)){
            $items = Category::where('title',$title)->orderBy($sort[0],$sort[1])->paginate($limit);
        } else {
            $items = Category::orderBy($sort[0], $sort[1])->paginate($limit);
        }

        return response()->json(['code' => 20000, 'message' => '分类查询成功', 'data' => $items]);
    }
    // 添加
    public function addCate(Request $request)
    {
        $title = trim($request->get('title'));
        $category_list = Category::where('title',$title)->get();
        if(count($category_list) > 0){
            return response()->json(['code' => 20004, 'message' => '该分类已存在']);
        } else {
            $category = new Category();
            $category->title = $title;
            $category->save();
            return response()->json(['code' => 20000, 'message' => '添加分类成功']);
        }
    }
    // 查一条
    public function getinfo(Request $request)
    {
        $id = $request->get('id');
        // redaySql(new DB);
        $category = Category::find($id);
        // showSql(new DB);
        return response()->json(['code' => 20000, 'message' => '查询分类信息成功', 'data' => $category]);
    }

    // 修改
    public function updateCate(Request $request)
    {
        $id = $request->get('id');
        $title = trim($request->get('title'));
        $category = Category::find($id);
        if(!empty($category->id)){
            $category_list = Category::where('title',$title)->first();
            if(!empty($category_list->id) && $category_list->id != $id){
                return response()->json(['code' => 20004, 'message' => '修改分类失败，分类已存在']);
            } else {    
                $category->title = $title;
                $category->save();
                return response()->json(['code' => 20000, 'message' => '修改分类成功']);
            }
        } else {
            return response()->json(['code' => 20004, 'message' => '修改分类失败，未找到该分类']);
        }
    }

    // 删除
    public function deleteCate(Request $request)
    {
        $id = $request->get('id');
        $category = Category::find($id);
        $category->delete();
        return response()->json(['code' => 20000, 'message' => '删除分类成功']);
    }
   
}
